package com.stylefeng.guns.rest.modular.users.controller;

import com.stylefeng.guns.rest.common.CommonResponse;
import com.stylefeng.guns.rest.common.enums.MsgCode;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.exception.BussinessException;
import com.stylefeng.guns.rest.common.persistence.model.Article;
import com.stylefeng.guns.rest.common.persistence.model.CenterData;
import com.stylefeng.guns.rest.common.persistence.model.SmsCode;
import com.stylefeng.guns.rest.common.persistence.model.User;
import com.stylefeng.guns.rest.common.utils.InputCheckUtil;
import com.stylefeng.guns.rest.common.utils.TextUtil;
import com.stylefeng.guns.rest.common.utils.aliyunoss.OSSUploadUtil;
import com.stylefeng.guns.rest.modular.artitle.service.ArticleService;
import com.stylefeng.guns.rest.modular.attent.controller.dto.AttentHotRequest;
import com.stylefeng.guns.rest.modular.attent.controller.dto.AttentUserResponse;
import com.stylefeng.guns.rest.modular.attent.service.AttentService;
import com.stylefeng.guns.rest.modular.attent.service.AttentUserService;
import com.stylefeng.guns.rest.modular.attent.service.CareService;
import com.stylefeng.guns.rest.modular.auth.controller.dto.AuthRequest;
import com.stylefeng.guns.rest.modular.auth.controller.dto.AuthResponse;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.auth.validator.IReqValidator;
import com.stylefeng.guns.rest.modular.sms.service.SmsCodeService;
import com.stylefeng.guns.rest.modular.users.controller.dto.*;
import com.stylefeng.guns.rest.modular.users.service.UserService;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by ASUS-PC on 2018/6/22.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private final Log logger = org.apache.commons.logging.LogFactory.getLog(this.getClass());
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Resource(name = "dbValidator")
    private IReqValidator reqValidator;
    @Autowired
    UserService userService;
    @Autowired
    SmsCodeService smsCodeService;
    @Autowired
    AttentService attentService;
    @Autowired
    AttentUserService attentUserService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CareService careService;

    //用户注册
    @RequestMapping(value = "/register" , method = RequestMethod.POST)
    public ResponseEntity<?> getCode(@RequestBody UserRegisterParam request){
        if(TextUtil.isEmpty(request.getPhone())
                || TextUtil.isEmpty(request.getSmsCode())
                || TextUtil.isEmpty(request.getPassword())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        if(TextUtil.isEmpty(request.getCountryCode())){
            request.setCountryCode("86");
        }
        if("86".equals(request.getPhone())){
            if(!InputCheckUtil.isVaildPhone(request.getPhone())){
                return ResponseEntity.ok(CommonResponse.okMsg(MsgCode.INVALID_PHONE_NUMBER,"账号不合法" , ""));
            }
        }
        SmsCode smsCode = smsCodeService.checkSmsCode(request.getPhone(),request.getSmsCode(),1);
        if(smsCode==null){
            throw new BussinessException(BizExceptionEnum.SMS_CODE_WRONG);
        }
        // todo 后续需要加入验证码3分钟过期校验
        if(((new Date().getTime())-smsCode.getUpdateTime().getTime())>3*60*1000){
            throw new BussinessException(BizExceptionEnum.SMS_CODE_DATE_OUT);
        }
        if(userService.inserUser(request)){
            return ResponseEntity.ok(CommonResponse.ok(null));
        }
        throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
    }

    //用户登陆
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public ResponseEntity<?> userLogin(@RequestBody AuthRequest authRequest){
        if(TextUtil.isEmpty(authRequest.getUserName())
                || TextUtil.isEmpty(authRequest.getPassword())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        boolean validate = reqValidator.validate(authRequest);
        if(validate){
            String randomKey = jwtTokenUtil.getRandomKey();
            String token = jwtTokenUtil.generateToken(authRequest.getUserName(), randomKey);
            User user = userService.login(authRequest);
            if(user==null){
                User u = userService.checkUserIsRegiset2(authRequest.getUserName());
                if(u == null){
                    throw new BussinessException(BizExceptionEnum.CAN_NOT_FIND_USER);
                }else {
                    throw new BussinessException(BizExceptionEnum.AUTH_REQUEST_ERROR);
                }
            }else {
                return ResponseEntity.ok(CommonResponse.ok("登录成功" , new AuthResponse(token,randomKey,user)));
            }
        }else {
            throw new BussinessException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }

    //用户详情
    @RequestMapping(value = "/detail" , method = RequestMethod.POST)
    public ResponseEntity<?> userDetail(@RequestBody UserInfoRequest request){
        if(request.getUserId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        User user = userService.selectUserByUserId(request.getUserId());

        if (user == null){
            throw new BussinessException(BizExceptionEnum.CAN_NOT_FIND_USER);
        }

        return ResponseEntity.ok(CommonResponse.ok(user));
    }

    //更新用户详情
    @RequestMapping(value = "/updateUserInfo" , method = RequestMethod.POST)
    public ResponseEntity<?> updateUserInfo(@RequestBody UpdateInfoRequest request){
        if (request.getUserId() == 0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        User user = userService.selectUserByUserId(request.getUserId());
        if (user == null){
            throw new BussinessException(BizExceptionEnum.CAN_NOT_FIND_USER);
        }
        if (!TextUtil.isEmpty(request.getAvatar())){
            user.setAvatar(request.getAvatar());
        }
        if (!TextUtil.isEmpty(request.getNickName())){
            user.setNickName(request.getNickName());
        }
        if(!TextUtil.isEmpty(request.getIntrodution())){
            user.setIntro(request.getIntrodution());
        }
        if (request.getAge()!=-1){
            user.setAge(request.getAge());
        }
        if (request.getSex()!=-1){
            user.setSex(request.getSex());
        }
        if(request.getIsPlan()!=-1){
            user.setIsPlan(request.getIsPlan());
        }
        if (userService.updateUserById(request.getUserId() , user)){
            return ResponseEntity.ok(CommonResponse.ok(user));
        }else {
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
    }

    /**
     * 重设密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/forgetPwd" , method = RequestMethod.POST)
    public ResponseEntity<?> forgetPwd(@RequestBody ForgetPwdRequest request){
        if (TextUtil.isEmpty(request.getMobile())
                || TextUtil.isEmpty(request.getCode())
                || TextUtil.isEmpty(request.getPwd())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        SmsCode s = smsCodeService.checkSmsCode(request.getMobile() ,  request.getCode(),2);
        if (s!=null){
            if (userService.updatePwdByMobile(request.getMobile() , request.getPwd())){
                return ResponseEntity.ok(CommonResponse.ok(null));
            }else {
                throw new BussinessException(BizExceptionEnum.SMS_CODE_DATE_OUT);
            }
        }else {
            throw new BussinessException(BizExceptionEnum.SMS_CODE_WRONG);
        }
    }


    /**
     * 更新用户头像
     * @param userId
     * @param
     * @return
     */
    @RequestMapping(value = "/uploadAvatar" , method = RequestMethod.POST)
    public ResponseEntity<?> updateAvatar(@RequestParam(value = "userId" , required = true) int userId,
                                          @RequestParam(value = "avatar" , required = true) MultipartFile file){
        if(userId==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        if(file==null || file.isEmpty()){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        logger.debug("publish file is :"+file.getOriginalFilename());
        String avatarPath = OSSUploadUtil.getInsance().uploadSingleImage(file);
        if(TextUtil.isEmpty(avatarPath)){
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
        User user = userService.selectUserByUserId(userId);
        if (user == null){
            throw new BussinessException(BizExceptionEnum.CAN_NOT_FIND_USER);
        }
        user.setAvatar(avatarPath);
        if (userService.updateUserById(userId , user)){
            return ResponseEntity.ok(CommonResponse.ok(user));
        }else {
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }

    }

    //获取我的粉丝列表
    @RequestMapping(value = "/getMyFens" , method = RequestMethod.POST)
    public ResponseEntity<?> getMyFens(@RequestBody AttentHotRequest request){
        if(request.getAttentId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        if(request.getPage()==0){
            request.setPage(1);
        }
        if(request.getSize()==0){
            request.setSize(20);
        }
        List<AttentUserResponse> lists = attentUserService.getFensUserList(request);
        if(lists!=null && lists.size()>0){
            for (AttentUserResponse entity:lists) {
                int isAttent = attentService.queryAttntByUser(request.getAttentId(),entity.getUserId());
                if(isAttent==1){
                    entity.setIsAttent(1);
                }else {
                    entity.setIsAttent(0);
                }
            }
        }
        return ResponseEntity.ok(CommonResponse.ok(lists));

    }


    //获取我的粉丝数量
    @RequestMapping(value = "/getMyDatas" , method = RequestMethod.POST)
    public ResponseEntity<?> getMyFens(@RequestBody UserInfoRequest request){
        if(request.getUserId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        CenterData centerData = new CenterData();
        //查询用户所有创作
        List<Article> articles = articleService.userAllArticleList(request);
        centerData.setMyArtitleNums(articles.size());
        //所有点赞数
        if(articles!=null && articles.size()>0){
            int careNums = 0;
            for (Article a:articles) {
                careNums = careNums+careService.queryAllCareByUser(a.getId());
            }
            centerData.setMyCareNums(careNums);
        }
        //查询用户所有关注的人
        List<AttentUserResponse> lists = attentUserService.getAllAttentUserList(request);
        centerData.setMyAttentsNums(lists.size());
        //查询用户所有粉丝
        List<AttentUserResponse> fensLists = attentUserService.getAllFensUserList(request);
        centerData.setMyFensNums(fensLists.size());
        //查询用户已点赞的数量
        int likeNums = careService.queryAllCareByUserId(request.getUserId());
        centerData.setMyLikeNums(likeNums);

        return ResponseEntity.ok(CommonResponse.ok(centerData));
    }

    //用户验证码登陆
    @RequestMapping(value = "/loginSms" , method = RequestMethod.POST)
    public ResponseEntity<?> usmsLogin(@RequestBody SmsLogin request){
        if(TextUtil.isEmpty(request.getPhone()) || TextUtil.isEmpty(request.getCode())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        SmsCode smsCode = smsCodeService.checkSmsCode(request.getPhone(),request.getCode(),3);
        if(smsCode==null){
            throw new BussinessException(BizExceptionEnum.SMS_CODE_WRONG);
        }
        // 验证码3分钟过期校验
        if(((new Date().getTime())-smsCode.getUpdateTime().getTime())>3*60*1000){
            throw new BussinessException(BizExceptionEnum.SMS_CODE_DATE_OUT);
        }
        if(TextUtil.isEmpty(request.getCountryCode())){
            request.setCountryCode("86");
        }
        String randomKey = jwtTokenUtil.getRandomKey();
        String token = jwtTokenUtil.generateToken(request.getPhone(), randomKey);
        User user = userService.checkUserIsRegiset2(request.getPhone());
        if (user == null){
            //用户不存在，则直接注册用户
            UserRegisterParam r = new UserRegisterParam();
            r.setPhone(request.getPhone());
            r.setPassword("");
            r.setCountryCode(request.getCountryCode());
            if(userService.inserUser(r)){
                User user1 = userService.checkUserIsRegiset2(request.getPhone());
                return ResponseEntity.ok(CommonResponse.ok("登录成功" , new AuthResponse(token,randomKey,user1)));
            }else {
                throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
            }
        }else {
            return ResponseEntity.ok(CommonResponse.ok("登录成功" , new AuthResponse(token,randomKey,user)));
        }
    }

}
